package com.wangzhen.jvm;

import java.util.Base64;

/**
 * 1、创建一个用于演示加载的Class文件，Hello.java ；在类文件中有一个静态代码块用户输出一段话
 * 2、使用javac命令编译这个java源文件
 * 3、使用mac 自带命令base64 com/wangzhen/jvm/Hello.class 获取base64编码之后的字符串
 * 4、在本类中将base64解码之后的byte数组（等于javac Hello.java 后生成的class文件 ）
 *    调用ClassLoader的defineClass方法 加载Hello这个类
 *
 * 5、备注：即使将Hello这个类删除的时候，也是不影响本类的执行。用于动态加载Class文件，代码保护
 */
public class CustomerClassLoaderDemo extends ClassLoader{

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        // 第一步：javac  com/wangzhen/jvm/Hello.java
        // 第二步：base64 com/wangzhen/jvm/Hello.class
        String helloBase64Class = "yv66vgAAADQAHAoABgAOCQAPABAIABEKABIAEwcAFAcAFQEABjxpbml0PgEAAygpVgEABENvZGUBAA9MaW5lTnVtYmVyVGFibGUBAAg8Y2xpbml0PgEAClNvdXJjZUZpbGUBAApIZWxsby5qYXZhDAAHAAgHABYMABcAGAEAC2hlbGxvIHdvcmxkBwAZDAAaABsBABZjb20vd2FuZ3poZW4vanZtL0hlbGxvAQAQamF2YS9sYW5nL09iamVjdAEAEGphdmEvbGFuZy9TeXN0ZW0BAANvdXQBABVMamF2YS9pby9QcmludFN0cmVhbTsBABNqYXZhL2lvL1ByaW50U3RyZWFtAQAHcHJpbnRsbgEAFShMamF2YS9sYW5nL1N0cmluZzspVgAhAAUABgAAAAAAAgABAAcACAABAAkAAAAdAAEAAQAAAAUqtwABsQAAAAEACgAAAAYAAQAAAAMACAALAAgAAQAJAAAAJQACAAAAAAAJsgACEgO2AASxAAAAAQAKAAAACgACAAAABgAIAAcAAQAMAAAAAgAN";
        byte[] bytes = Base64.getDecoder().decode(helloBase64Class);
        return defineClass(name, bytes, 0, bytes.length);
    }

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        new CustomerClassLoaderDemo().findClass("com.wangzhen.jvm.Hello").newInstance();
        //Base64.getDecoder().decode()
    }
}
